<template>
  <div ref="bar" style="width:50%;height:400px"></div>
</template>
<script>
import echarts from "echarts";
export default {
  props: ['title', 'data', 'data-key'],
  data () {
    return {
      chart: null
    }
  },
  watch: {
    data: {
      handler () {
        this.chart.setOption(this.getOpt())
      },
      deep: true
    }
  },
  mounted () {
    this.chart = echarts.init(this.$refs.bar, 'light')
    this.chart.setOption(this.getOpt())
  },
  methods: {
    getOpt () {
      const colors = [
        '#37A2DA',
        '#32C5E9',
        '#67E0E3',
        '#9FE6B8',
        '#FFDB5C',
        '#ff9f7f',
        '#fb7293',
        '#E062AE',
        '#E690D1',
        '#e7bcf3',
        '#9d96f5',
        '#8378EA',
        '#96BFFF'
      ]
      const seriesData = []
      const yData = []
      this.data.forEach((item, i) => {
        let merchantName = item.merchantName
        seriesData.unshift({
          name: merchantName,
          value: item[this.dataKey],
          itemStyle: {
            color: colors[i]
          }
        })
        // 防止y轴公司名字过长
        if (merchantName && merchantName.length > 8) {
          merchantName = merchantName.slice(0, 8)
          merchantName = merchantName + '...'
        }
        yData.unshift(merchantName)
      })

      return {
        title: {
          text: this.title
        },
        tooltip: {},
        grid: {
          left: '40%'
        },
        yAxis: {
          type: 'category',
          data: yData
        },
        xAxis: {
          type: 'value',
          show: false
        },
        series: [
          {
            type: 'bar',
            barWidth: 15,
            data: seriesData,
            barMinHeight: 5
          }
        ]
      }
    }
  }
}
</script>
